package net.mayee.alice.common;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

public class IpUtils extends HttpServlet {

	private static final long serialVersionUID = 276049553107289723L;

	public static String getClientRealIP(HttpServletRequest request) {
		String IP = request.getHeader("x-forwarded-for");
		if (null == IP || 0 == IP.length() || "unknown".equalsIgnoreCase(IP)) {
			IP = request.getHeader("Proxy-Client-IP");
		}
		if (null == IP || 0 == IP.length() || "unknown".equalsIgnoreCase(IP)) {
			IP = request.getHeader("WL-Proxy-Client-IP");
		}
		if (null == IP || 0 == IP.length() || "unknown".equalsIgnoreCase(IP)) {
			IP = request.getRemoteAddr();
		}
		if (null != IP && IP.length() > 15) {
			if (IP.indexOf(",") > 0) {
				IP = IP.substring(0, IP.indexOf(","));
			}
		}
		return IP;
	}

	public static String getClientRealIP2(HttpServletRequest request) {
		String IP = null;
		Enumeration enu = request.getHeaderNames();
		while (enu.hasMoreElements()) {
			String name = (String) enu.nextElement();
			if ("X-Forwarded-For".equalsIgnoreCase(name)) {
				IP = request.getHeader(name);
			} else if ("Proxy-Client-IP".equalsIgnoreCase(name)) {
				IP = request.getHeader(name);
			} else if ("WL-Proxy-Client-IP".equalsIgnoreCase(name)) {
				IP = request.getHeader(name);
			}
			if (null != IP && 0 != IP.length())
				break;
		}
		if (null == IP || 0 == IP.length()) {
			IP = request.getRemoteAddr();
		}
		return IP;
	}
}